package com.zjh.es;

import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicInteger;

public class ReactiveDemo {
    public static void main(String[] args) throws InterruptedException {
        Flow.Publisher<Object> publisher=new Flow.Publisher<Object>() {
            @Override
            public void subscribe(Flow.Subscriber<? super Object> subscriber) {
                Flow.Subscription subscription = new Flow.Subscription() {
                   AtomicInteger count =  new AtomicInteger(10);
                   boolean cancel = false;
                    @Override
                    public void request(long n) {
                    // 在publisher 中生成数据，交给subscriber去处理
                        for (int i = 0; i < count.get() && !cancel; i++) {
                            int currentCount = count.getAndDecrement();
                            if (currentCount==5 ){
                                subscriber.onComplete();
                                break;
                            }else{
                                subscriber.onNext(Thread.currentThread().getName()+"-"+currentCount);
                            }
                        }
                    }
                    @Override
                    public void cancel() {
                        this.cancel = true;
                        System.out.println("取消订阅");

                    }
                };
                subscriber.onSubscribe(subscription);
            }
        };

        Flow.Subscriber<Object> subscriber = new Flow.Subscriber<>() {
            Flow.Subscription subscription;
            @Override
            public void onSubscribe(Flow.Subscription subscription) {
                this.subscription = subscription;
                System.out.println("开始订阅");
                subscription.request(1);
            }
            @Override
            public void onNext(Object item) {
                System.out.println("收到数据："+Thread.currentThread().getName() + item);
                subscription.request(1);
            }
            @Override
            public void onError(Throwable throwable) {
                System.out.println("消息有误");
            }
            @Override
            public void onComplete() {
                System.out.println("数据接受完毕");
                subscription.cancel();
            }
        };

        publisher.subscribe(subscriber);
        Thread.sleep(2000);

    }
}
